<template>
  <div class="project-form">
    <el-card>
      <!-- // 面包屑导航 -->
      <div>
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/index' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>
            <a href="/project">用户管理</a>
          </el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <br />
      <!-- // 筛选条件 -->
      <el-form
        ref="searchForm"
        :inline="true"
        :model="searchForm"
        size="small"
        label-width="80px"
      >
        <el-form-item prop="username" class="form-username" label="登录账号">
          <el-input
            v-model="searchForm.username"
            placeholder="请输入登录账号"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item prop="nickname" class="form-nickname" label="用户昵称">
          <el-input
            v-model="searchForm.nickname"
            placeholder="请输入用户昵称"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item prop="is_delete" class="form-is_delete" label="用户状态">
          <el-select v-model="searchForm.is_delete" placeholder="请选择状态">
            <el-option
              v-for="item in items"
              :key="item.text"
              :label="item.text"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            查询
          </el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button type="success" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table
        class="table"
        :data="tableData"
        border
        style="width: 100%"
        v-loading="loading"
        size="medium"
      >
        <el-table-column label="ID" type="index" width="50"> </el-table-column>
        <el-table-column prop="username" label="登录账号" width="220">
        </el-table-column>
        <el-table-column prop="nickname" label="用户昵称" width="220">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="220">
        </el-table-column>
        <el-table-column prop="is_delete" label="用户状态" width="100">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.is_delete == false ? 'success' : 'danger'"
              >{{ scope.row.is_delete == false ? "正常" : "禁用" }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column prop="mobile" label="手机号" width="200">
        </el-table-column>
        <el-table-column
          prop="is_admin"
          :formatter="dateFormat"
          label="用户权限"
          width="100"
        >
          <template slot-scope="scope">
            <el-tag :type="scope.row.is_admin == 1 ? 'primary' : 'info'">{{
              scope.row.is_admin == 1 ? "管理员" : "普通用户"
            }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="更新人" width="100" prop="updator">
          <template slot-scope="scope">
            <el-tag type="primary" effect="plain" size="medium">
              {{ scope.row.updator }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
          prop="update_time"
          :formatter="dateFormat"
          label="更新时间"
          width="160"
        >
        </el-table-column>

        <!-- 操作按钮 -->
        <el-table-column label="操作" width="300" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click.native.prevent="handleEdit(scope.row)"
              type="primary"
            >
              编辑
            </el-button>
            <el-button
              v-if="scope.row.is_delete == false"
              size="mini"
              type="danger"
              @click="changeStatus(scope.row)"
            >
              禁用
            </el-button>
            <el-button
              v-else
              size="mini"
              type="success"
              @click="changeStatus(scope.row)"
            >
              启用
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <br />

      <!-- // 分页展示 -->
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        :page-sizes="[12, 20, 50, 100]"
        :page-size="pagination.pageSize"
        :total="pagination.total"
        :disabled="loading"
        :current-page.sync="pagination.page"
        @current-change="loadUsers(pagination.page)"
      >
      </el-pagination>
    </el-card>

    <!-- 新增表单弹窗 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogFormVisible"
      :modal-append-to-body="false"
      width="600px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @closed="initDialog"
    >
      <el-form
        :model="addUserForm"
        ref="addUserForm"
        :rules="addUserFormRules"
        label-width="100px"
      >
        <el-form-item prop="nickname" label="用户昵称">
          <el-input v-model="addUserForm.nickname"> </el-input>
        </el-form-item>
        <el-form-item prop="username" label="登录账号">
          <el-input v-model="addUserForm.username" :disabled="disabled">
          </el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input
            v-model="addUserForm.password"
            :disabled="disabled"
            type="password"
          >
          </el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="addUserForm.email"> </el-input>
        </el-form-item>
        <el-form-item prop="mobile" label="手机号">
          <el-input v-model="addUserForm.mobile"> </el-input>
        </el-form-item>
        <el-form-item prop="is_admin" label="设为管理员">
          <el-switch
            v-model="addUserForm.is_admin"
            active-color="#13ce66"
          ></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false" size="medium"
          >取 消</el-button
        >
        <el-button type="primary" @click="submitForm" size="medium"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getUserInfo,
  addUserInfo,
  deleteUserInfo,
  updateUserInfo,
  updateStatus
} from "@/api/user";
import moment from "moment";

export default {
  name: "",
  props: {},
  components: {},
  data() {
    return {
      // 查询表单
      searchForm: {
        username: undefined,
        nickname: undefined,
        is_admin: undefined,
        email: undefined,
        is_disable: undefined
      },

      title: "",
      tableData: [],

      items: [
        { type: "danger", text: "禁用", value: 0 },
        { type: "success", text: "正常", value: 1 },
        { type: "", text: "全部", value: undefined }
      ],
      loading: true,

      // 【分页属性】
      pagination: {
        total: 0,
        page: 1,
        pageSize: 12
      },

      // 弹窗控制
      dialogFormVisible: false,

      // 新增表单属性
      addUserForm: {
        nickname: undefined,
        username: undefined,
        password: undefined,
        email: undefined,
        mobile: undefined,
        is_admin: false
      },
      disabled: true,

      // 表单属性验证
      addUserFormRules: {
        nickname: [
          {
            required: true,
            message: "请输入用户名称",
            trigger: blur
          }
        ],
        username: [
          {
            required: true,
            message: "请输入登录账号",
            trigger: blur
          }
        ],
        password: [
          {
            message: "请输入登录密码",
            trigger: blur
          }
        ],
        email: [
          {
            required: true,
            max: 50,
            min: 3,
            message: "请输入用户邮箱",
            trigger: blur
          }
        ],
        mobile: [
          {
            required: true,
            message: "请输入手机号",
            trigger: blur
          }
        ]
      }
    };
  },
  computed: {},
  watch: {},
  created() {
    // 加载项目方法，进入项目就调用此方法
    this.loadUsers();
  },
  mounted() {},
  methods: {
    handleSizeChange(size) {
      this.pagination.pageSize = size;
      this.loadUsers();
    },

    loadUsers(page = 1) {
      getUserInfo({
        page,
        page_size: this.pagination.pageSize
      })
        .then(res => {
          this.tableData = res.data.result;
          this.pagination.total = res.data.total;
          this.loading = false;
        })
        .catch(err => {
          console.log("错误信息：" + err);
        });
    },

    // 关闭弹窗
    initDialog(flag) {
      this.addUserForm = {
        nickname: undefined,
        username: undefined,
        password: undefined,
        email: undefined,
        mobile: undefined,
        is_admin: false
      };
      this.dialogFormVisible = false;
    },

    // 查询方法
    handleSearch(page = 1) {
      getUserInfo(this.searchForm, { page }).then(res => {
        this.tableData = res.data.result;
        this.total = res.data.total;
        // 关闭加载提示
        this.loading = false;
      });
    },

    // 重置Form表单
    resetForm() {
      this.$refs["searchForm"].resetFields();
      this.loadUsers();
    },

    // 修改数据
    handleEdit(row) {
      this.title = "编辑用户";
      this.disabled = true;
      this.addUserForm = row;
      this.dialogFormVisible = true;
    },

    // 添加项目操作
    handleAdd() {
      this.title = "新增用户";
      this.disabled = false;
      this.dialogFormVisible = true;
    },

    // 新增表单确定按钮点击事件
    submitForm() {
      // 校验提交表单
      this.$refs["addUserForm"].validate(valid => {
        // 如果表单验证失败，停止请求提交
        if (!valid) {
          return;
        }
        if (!this.addUserForm.id) {
          addUserInfo(this.addUserForm)
            .then(res => {
              if (res.data.code === 200) {
                this.$message({
                  type: "success",
                  message: "新增成功"
                });
                this.dialogFormVisible = false;
              } else {
                this.$message.error(res.data.msg);
              }
              this.loadUsers();
            })
            .catch(err => {
              this.$message.error("新增失败：" + err);
            });
        } else {
          updateUserInfo(this.addUserForm)
            .then(res => {
              if (res.data.code === 200) {
                this.$message({
                  type: "success",
                  message: "编辑成功"
                });
                this.dialogFormVisible = false;
              } else {
                this.$message.error(res.data.msg);
              }
              this.loadUsers();
            })
            .catch(err => {
              this.$message.error("编辑失败：" + err);
            });
        }
      });
    },

    // 删除操作
    changeStatus(row) {
      if (row.is_delete == false) {
        var action = " 禁用 ";
        var state = false;
      } else {
        var action = " 启用 ";
        var state = true;
      }
      this.$confirm("确定" + action + "该用户?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let form = {
            id: row.id,
            is_delete: state
          };
          updateStatus(form)
            .then(res => {
              if (res.data.code === 200) {
                this.$message({
                  type: "success",
                  message: action + "成功"
                });
              } else {
                this.$message.error(res.data.msg);
              }
              this.loadUsers();
            })
            .catch(err => {
              this.$message.error(action + "失败：" + err);
            });
        })
        .catch(err => {
          this.$message({
            type: "info",
            message: "已取消" + action
          });
        });
    },

    // 编写日期格式化方法
    dateFormat: function(row, column) {
      const date = row[column.property];
      if (date === undefined) {
        return "";
      }
      // 这里的格式根据需求修改
      return moment(date).format("YYYY-MM-DD HH:mm:ss");
    }
  }
};
</script>

<style lang="less"></style>
